package cn.intotw.pp.server.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author Chenxiang
 * @Description: PP服务器类
 * @create 2018/8/20 15:22
 */
@Log4j
@Component(value = "ppServer")
public class PPServer {
    @Value("${server.port}")
    private int port;
    public void start() {
        EventLoopGroup bossEventLoop=new NioEventLoopGroup(1);
        EventLoopGroup workerEventLoop=new NioEventLoopGroup(5);
        try {
            ServerBootstrap b=new ServerBootstrap();
            b.group(bossEventLoop,workerEventLoop)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(2048))
                    .childHandler(new PPServerChannelInitializer());

            ChannelFuture f=b.bind(port).sync();
            f.channel().closeFuture().sync();
        }
        catch (Exception e)
        {
            log.error("",e);
        }
        finally {
            bossEventLoop.shutdownGracefully();
            workerEventLoop.shutdownGracefully();
        }
    }
}